// pages/order/order.js
const app = getApp();
let timer;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    StoreName : "",
    background: ['https://636c-cloud1-9g5qe48meb38bfec-1310438790.tcb.qcloud.la/11c52b941b8b91c6539488ec93f0337.png?sign=cba6311dff24e28928875e8961bb4854&t=1648356212',
                   'https://636c-cloud1-9g5qe48meb38bfec-1310438790.tcb.qcloud.la/81444472fc9c181d7f871f1bbf6801b.png?sign=fe07224a13ecc77bee6c9a310bd82d42&t=1648356282'],
    viewTo: "",
    viewToLeft: "",
    listHeight: 300,
    activeIndex: 0,
    tabIndex: 0,
    showModal: false,
    showCart: false,
    heigthArr: [],
    cart: [],
    totalMoney: 0,
    /*food: [{
        titleId: "title1",         //类别id
        title: "拉面",             //类别名字
        foodCount: 0,             //类别菜品点击总数，初始化为0
        items: [{
            foodId: 1,             //int 型
            name: "大骨浓汤猪软骨拉面",       //菜名
            price: 41.65,             //价格
            note: "猪软骨筋肉软糯多胶原。爽嫩的笋条、搭配浓香骨汤齿颊留香，根本停不下来！", //菜品描述
            count: 0,              //菜品点击数，初始化为0
            imgURL:'http://localhost:8080/img/92643a5751904b87bc8fc6ac5fa6794a-1.png'
          },
          {
            foodId: "d0002",
            name: "骨汤番茄肥牛拉面",
            price: 41.00,
            note: "一口弹牙小嫩牛，酸爽多汁大番茄。经典番茄肥牛口味，配以浓香骨汤，口感鲜美酸爽。",
            count: 0,
            imgURL:'http://localhost:8080/img/2.png'
          },
          {
            foodId: 3,
            name: "味凯酸酸辣辣面",
            price: 32.00,
            note: "味凯招聘拉面！酸爽口味搭配蜜汁猪颈肉，配以酸辣鲜香骨汤，唇齿留香，酸爽劲爆！",
            zan: 34,
            count: 0,
            imgURL:'http://localhost:8080/img/3.png'
          },
          {
            foodId: 4,             //int 型
            name: "麻辣牛肉拉面",       //菜名
            price: 43.00,             //价格
            note: "精选麻辣牛肉浇头，浇以麻辣红汤，辛香升级、香辣过瘾。", //菜品描述
            count: 0,              //菜品点击数，初始化为0
            imgURL:'http://localhost:8080/img/4.png'
          },
          {
            foodId: 5,
            name: "潮汕叉烧拉面",
            price: 32.30,
            note: "潮汕叉烧风味，两分肥八分瘦。浓厚豚骨汤面，搭配厚切叉烧，浓香满足，大快朵颐。",
            count: 0,
            imgURL:'http://localhost:8080/img/5.png'
          },
          {
            foodId: 6,
            name: "揭阳菌菇拉面",
            price: 30.00,
            note: "浓厚骨汤搭配清爽菌菇，解腻的同时带给你鲜美的口感。",
            count: 0,
            imgURL:'http://localhost:8080/img/6.png'
          }
        ]
      },
      {
        titleId: "title2",
        title: "饭食",
        foodCount: 0,
        items: [{
            foodId: 4,
            name: "味凯烧牛肉饭",
            price: 42.00,
            note: "味凯招牌炒饭，精选新鲜牛肉，口感鲜嫩，搭配秘制酱料，米饭粒粒分明，绝对好吃。",
            count: 0,
            imgURL:'http://localhost:8080/img/703163751417493fba7b59621c70d544-2.png'
          },
          {
            foodId: 5,
            name: "潮州炒饭",
            price: 37.00,
            note: "传承中国潮州手艺，选用鸡蛋、葱花、叉烧，铁板炒制，颗粒分明满口留香。",
            count: 0,
            imgURL:'http://localhost:8080/img/7.png'
          },
          {
            foodId: 6,
            name: "麻麻辣辣牛肉饭",
            price: 41.00,
            note: "精制麻辣酱料，混合牛肉，大火翻炒，辛香入味。精选草场牛腱肉，猛火爆炒小麻椒。",
            count: 0,
            imgURL:'http://localhost:8080/img/8.png'
          },
          {
            foodId: 7,
            name: "猪软骨鳗鱼丼",
            price: 48.00,
            note: "鳗鱼搭配猪软骨肉质丝嫩软糯大满足。",
            count: 0,
            imgURL:'http://localhost:8080/img/9.png'
          }
        ]
      },
      {
        titleId: "title3",
        title: "小食",
        foodCount: 0,
        items: [{
            foodId: 7,
            name: "黑猪肉煎饺",
            price: 16.00,
            note: "黑猪肉细剁调馅，制饺下锅煎至底部金黄，馅鲜皮脆。",
            count: 0,
            imgURL:'http://localhost:8080/img/11.png'
          },
          {
            foodId: 8,
            name: "汕头章鱼烧",
            price: 18.00,
            note: "纯正汕头风味，外皮酥脆软糯、章鱼鲜嫩Q弹！",
            count: 0,
            imgURL:'http://localhost:8080/img/12.png'
          },
          {
            foodId: 9,
            name: "金针菇牛肉卷",
            price: 22.00,
            note: "厚实肥牛卷上鲜美的金针菇煎制，肉香与菌菇的鲜味交融，一口一个。",
            count: 0,
            imgURL:'http://localhost:8080/img/13.png'
          }
        ]
      },
      {
        titleId: "title4",
        title: "小食拼盘",
        foodCount: 0,
        items: [{
            foodId: 10,
            name: "小食拼盘",
            price: 22.00,
            note: "多种精选美食，一盘享受！",
            count: 0,
            imgURL:'http://localhost:8080/img/17.png'
          }
        ]
      },
      {
        titleId: "title5",
        title: "餐前凉菜",
        foodCount: 0,
        items: [{
            foodId: 13,
            name: "味凯海藻",
            price: 16.00,
            note: "味凯精选海藻，清凉开胃。",
            count: 0,
            imgURL:'http://localhost:8080/img/14.png'
          },
          {
            foodId: 14,
            name: "味凯泡菜",
            price: 16.00,
            note: "精选韩国泡菜。",
            count: 0,
            imgURL:'http://localhost:8080/img/15.png'
          },
          {
            foodId: 15,
            name: "味凯玉米",
            price: 16.00,
            note: "精选新鲜玉米粒。",
            count: 0,
            imgURL:'http://localhost:8080/img/16.png'
          }
        ]
      },
      {
        titleId: "title6",
        title: "饮料",
        foodCount: 0,
        items: [{
            foodId: 16,
            name: "可乐",
            price: 5.00,
            note: "畅爽可乐。",
            count: 0,
            imgURL:'http://localhost:8080/img/20.png'
          },
          {
            foodId: 17,
            name: "雪碧",
            price: 5.00,
            note: "清爽雪碧。",
            count: 0,
            imgURL:'http://localhost:8080/img/19.png'
          }
        ]
      },
      {
        titleId: "title7",
        title: "皇家御用",
        foodCount: 0,
        items: [{
            foodId: 19,
            name: "凯王十三世秘制皇家豚骨拉面",
            price: 169.00,
            note: "凯王十三世皇家御用大厨秘制的豚骨拉面，仅为到访餐厅的各界特权人士与世袭贵族享用。",
            count: 0,
            imgURL:'http://localhost:8080/img/14.png'
          }
        ]
      }
    
    ]*/
    food:[],
    show : false,
    current_des : "",
    current_img : "",
    current_name : "",
    current_price : "",
  },


  click:function (res) {
      this.setData({
          show : !this.data.show,
          current_des : res.currentTarget.dataset.des,
          current_img : res.currentTarget.dataset.img,
          current_name : res.currentTarget.dataset.name,
          current_price : res.currentTarget.dataset.price,
      })
      console.log(res);
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
        console.log("在order页面获取canteenId: "+wx.getStorageSync('CanteenId'));
        var that=this;
        wx.request({
          url: 'http://localhost:8080/showDishes?restaurant_id='+wx.getStorageSync('CanteenId'),
          success:function (res) {
              console.log(res);
              let food = that.data.food;
              that.setData({
                  food : res.data,
                  StoreName : wx.getStorageSync('CanteenName')
                })
              console.log("本地拿到的："+that.data.food);
          }
        })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let height1, height2;
    let res = wx.getSystemInfoSync();
    let winHeight = res.windowHeight;
    let query = wx.createSelectorQuery();
    query.select(".head").boundingClientRect();
    query.exec(res => {
      height1 = res[0].height;
      let query1 = wx.createSelectorQuery();
      query1.select(".tab").boundingClientRect();
      query1.exec(res => {
        height2 = res[0].height;
        this.setData({
          listHeight: winHeight - height1 - height2
        });
        this.calculateHeight();
      });
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  selectFood(e) {
    this.setData({
      activeIndex: e.target.dataset.index,
      viewTo: e.target.dataset.titleid
    });
  },
  calculateHeight() {
    let heigthArr = [];
    let height = 0;
    heigthArr.push(height);
    var query = wx.createSelectorQuery();
    query.selectAll(".title-group").boundingClientRect();
    query.exec(res => {
      for (let i = 0; i < res[0].length; i++) {
        //console.log(res[0][i])
        height += parseInt(res[0][i].height);
        heigthArr.push(height);
      }
      this.setData({
        heigthArr: heigthArr
      });
    });
  },
  // 手机端有延迟 节流函数效果不好 用防抖函数凑合
  scroll(e) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      let srollTop = e.detail.scrollTop;
      for (let i = 0; i < this.data.heigthArr.length; i++) {
        if (
          srollTop >= this.data.heigthArr[i] &&
          srollTop < this.data.heigthArr[i + 1] &&
          this.data.activeIndex != i
        ) {
          this.setData({
            activeIndex: i
          });
          if (i < 3) {
            this.setData({
              viewToLeft: 'title1left'
            })
          } else {
            this.setData({
              viewToLeft: 'title' + (i - 2) + 'left'
            })
          }
          return;
        }
      }
    }, 100)
  },
  add(e) {
    let groupindex = e.target.dataset.groupindex;
    let index = e.target.dataset.index;
    let countMsg =
      "food[" +
      groupindex +
      "].items[" +
      index +
      "].count";
    let count = this.data.food[groupindex].items[
      index
    ].count;
    let foodCountMsg = "food[" + groupindex + "].foodCount";
    let foodCount = this.data.food[groupindex].foodCount;
    //console.log(foodCount);
    let dish_id = this.data.food[groupindex].items[
      index
    ].dish_id;
    //console.log(dish_id);
    count += 1;
    foodCount += 1;
    this.setData({
      [countMsg]: count, //数据的局部更新
      [foodCountMsg]: foodCount
    });
    let cart = this.data.cart;
    let hasCart = false;
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].dish_id == dish_id) {
        hasCart = true;
        break;
      }
    }
    if (hasCart) {
      cart[i].count++;
    } else {
      cart.push({ ...this.data.food[groupindex].items[index],
        groupindex
      });
    }
    let totalMoney = this.data.totalMoney;
    totalMoney += this.data.food[groupindex].items[
      index
    ].dish_price;
    this.setData({
      cart: cart,
      totalMoney: totalMoney
    });
  },
  reduce(e) {
    let groupindex = e.target.dataset.groupindex;
    let index = e.target.dataset.index;
    let countMsg =
      "food[" +
      groupindex +
      "].items[" +
      index +
      "].count";
    let count = this.data.food[groupindex].items[
      index
    ].count;
    let foodCountMsg = "food[" + groupindex + "].foodCount";
    let foodCount = this.data.food[groupindex].foodCount;
    let dish_id = this.data.food[groupindex].items[
      index
    ].dish_id;
    count -= 1;
    foodCount -= 1;
    this.setData({
      [countMsg]: count,
      [foodCountMsg]: foodCount
    });
    let cart = this.data.cart;
    for (var i = 0; i < cart.length; i++) {
      if (cart[i].dish_id == dish_id) {
        if (cart[i].count == 1) {
          cart.splice(i, 1);
        } else {
          cart[i].count--;
        }
        break;
      }
    }
    let totalMoney = this.data.totalMoney;
    totalMoney -= this.data.food[groupindex].items[
      index
    ].dish_price;
    this.setData({
      cart: cart,
      totalMoney: totalMoney
    });
  },
  listCart() {
    if (this.data.cart.length > 0) {
      this.setData({
        showCart: !this.data.showCart
      })
    }
  },
  deliver(){
    if (this.data.cart.length > 0) {
        console.log(this.data.cart);
        console.log(this.data.totalMoney);
    }
    wx.setStorageSync('goodcart',this.data.cart);
    wx.setStorageSync('totalmoney',this.data.totalMoney);
    wx.navigateTo({
      url: './confirm_order/confirm_order',
    })
  },
  selectTabItem(e) {
    if (e.target.dataset.index) {
      this.setData({
        tabIndex: e.target.dataset.index
      });
    }
  },
  preventScrollSwiper() {
    return false;
  },
  showStoreDetail() {
    this.setData({
      showModal: true
    });
  },
  closeModal(e) {
    this.setData({
      showModal: false
    });
  }
});